<?php

/**
 * Description of View
 *
 * @author Francis Adu-Gyamfi
 */
class View {

    /**
     * The controller class to render contents from
     * 
     * @var Controller
     */
    protected $controller = NULL;
    /**
     * An array of variables to use for the rendering
     * 
     * @var array
     */
    protected $variables = array();
    /**
     * The file to use for the View rendering
     * @var string
     */
    protected $template = "index.php";

	/**
	 * Will hold references to the helpers defined in the controller
	 */
	protected $helpers = array('HTML','String');

    public function __construct(&$controller, $template = NULL) {

        if (!is_null($controller)) {
            $this->controller = $controller;
			$this->variables = $controller->variables;
        }

        if (!is_null($template)) {
            $this->template = $template;
        }
		
		// initiate the helper classes available for use by this Controller
		if( $this->helpers != NULL ) {
            foreach($this->helpers as $helper) {
                if( class_exists($helper) && is_subclass_of($helper, 'Helper') ) {
                    $this->{$helper} = new $helper($this->controller);
                }
            }
        }
    }

    /**
     * Sets a variable to included or made available for the rendering process
     * 
     * @param mixed $key
     * @param mixed $variable 
     */
    public function set($key, $variable = NULL) {
        if (is_null($key)) {
            throw new InvalidArgumentException("A valid variable or array must be passed");
        }

        // consider the case where an array of variables can be passed instead
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                $this->variables[$k] = $v;
            }
        }

        if (is_string($key) && !is_null($variable)) {
            $this->variables[$key] = $variable;
        }
    }

    /**
     * Loads the global site object and renders the controller data to the template
     * in the theme
     * 
     * @global Site $site 
     */
    public function render() {
        global $site;

        // Load variables
        foreach ($this->variables as $key => $value) {
            $$key = $value;
        }

        // next we need to load the specific theme / template news file
        // the $themeFolder variable is created in the site selector
        $themeFile = $site->theme->path('pages/' . $this->template);
        $indexFile = $site->theme->path('pages/index.php');

        if (file_exists($themeFile)) {
            include( $themeFile );
        } else {
            include( $indexFile );
        }
    }

}

?>
